<template>
  <div v-if="show" class="script-detail-backdrop" @click="closeModal">
    <div class="script-detail-modal" @click.stop>
      <!-- 关闭按钮 -->
      <button @click="closeModal" class="close-btn">×</button>
      
      <!-- 图片轮播区域 -->
      <div class="images-section" v-if="scriptImages.length > 0">
        <ImageCarousel 
          :images="scriptImages"
          :scriptId="scriptId"
          :autoPlay="true"
          :interval="4000"
          :enableClick="true"
        />
      </div>
      
      <!-- 无图片时的占位符 -->
      <div v-else class="no-images-placeholder">
        <div class="placeholder-content">
          <div class="placeholder-icon">📷</div>
          <p>此剧本暂无图片</p>
          <small>上传剧本时可以添加图片</small>
        </div>
      </div>

      <!-- 标签页导航 -->
      <div class="tabs-nav">
        <button 
          v-for="tab in tabs" 
          :key="tab.key"
          @click="currentTab = tab.key"
          :class="['tab-btn', { active: currentTab === tab.key }]"
        >
          {{ tab.name }}
        </button>
      </div>

      <!-- 内容区域容器 -->
      <div class="modal-content-area">
        <!-- 标签页内容 -->
        <div class="tab-content">
          
          <!-- 加载状态 -->
          <div v-if="isLoading" class="loading-state">
            <div class="loading-spinner"></div>
            <p>加载剧本数据中...</p>
          </div>
        
        <!-- 基本信息 -->
        <div v-else-if="currentTab === 'basic'" class="tab-panel">
          <div class="basic-info">
            <div class="script-header">
              <h2 class="script-name">{{ scriptData.name }}</h2>
              <div class="script-meta">
                <span class="author">作者: {{ scriptData.author || '未知' }}</span>
                <span class="level">难度: {{ scriptData.level || 'Intermediate' }}</span>
              </div>
            </div>
            
            <div class="script-description" v-if="scriptData.description">
              <h3>剧本介绍</h3>
              <p>{{ scriptData.description }}</p>
            </div>
          </div>
        </div>

        <!-- 角色数据 -->
        <div v-else-if="currentTab === 'roles'" class="tab-panel">
          <div class="roles-section">
            

            
            <div v-for="team in roleTeams" :key="team.key" class="role-team">
              <div class="team-header" @click="toggleTeamExpansion(team.key)">
                <h3 class="team-title">{{ team.name }}</h3>
                <div class="team-count">({{ team.roles.length }}个角色)</div>
                <div class="expand-icon" :class="{ expanded: isTeamExpanded(team.key) }">
                  {{ isTeamExpanded(team.key) ? '▼' : '▶' }}
                </div>
              </div>
              <div class="roles-grid" v-show="isTeamExpanded(team.key)">
                <div 
                  v-for="role in team.roles" 
                  :key="role.id" 
                  class="role-card"
                >
                  <div class="role-header">
                    <img 
                      v-if="role.image" 
                      :src="role.image" 
                      :alt="role.name"
                      class="role-icon"
                    />
                    <h4 class="role-name">{{ role.name }}</h4>
                  </div>
                  <div class="role-ability">
                    <p>{{ role.ability }}</p>
                  </div>
                </div>
              </div>
            </div>
            

          </div>
        </div>

        <!-- 游戏规则 -->
        <div v-else-if="currentTab === 'rules'" class="tab-panel">
          <div class="rules-section">
            <div class="night-order">
              <h3>夜晚行动顺序</h3>
              <div class="order-lists">
                <div class="first-night">
                  <h4>首夜</h4>
                  <ol>
                    <li v-for="role in firstNightRoles" :key="role.id">
                      {{ role.name }} - {{ role.firstNightReminder }}
                    </li>
                  </ol>
                </div>
                <div class="other-nights">
                  <h4>其他夜晚</h4>
                  <ol>
                    <li v-for="role in otherNightRoles" :key="role.id">
                      {{ role.name }} - {{ role.otherNightReminder }}
                    </li>
                  </ol>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 系列版本 -->
        <div v-else-if="currentTab === 'series'" class="tab-panel">
          <div class="series-section">
            <h3>系列版本</h3>
            <div class="series-list" v-if="seriesVersions && seriesVersions.length > 0">
              <div 
                v-for="version in seriesVersions" 
                :key="version.id"
                class="version-item"
                :class="{ 'current': version.id === scriptId }"
                @click="switchToVersion(version)"
              >
                <div class="version-info">
                  <h4>{{ version.name }}</h4>
                  <span class="version-number">v{{ version.version }}</span>
                </div>
                <div class="version-status">
                  <span v-if="version.id === scriptId" class="current-badge">当前版本</span>
                </div>
              </div>
            </div>
            <div v-else class="no-series">
              <p>此剧本不属于任何系列</p>
            </div>
          </div>
        </div>
      </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button @click="downloadImages" class="action-btn download-btn">
          📥 下载图片
        </button>
        <button @click="useScript" class="action-btn use-btn">
          🎮 使用剧本
        </button>
      </div>

      <!-- 图片下载选择模态框 -->
      <div v-if="showDownloadModal" class="download-modal-backdrop" @click="closeDownloadModal">
        <div class="download-modal" @click.stop>
          <div class="modal-header">
            <h3>选择要下载的图片</h3>
            <button @click="closeDownloadModal" class="close-btn">×</button>
          </div>
          <div class="modal-content">
            <div class="download-options">
              <label class="select-all">
                <input 
                  type="checkbox" 
                  v-model="selectAllImages"
                />
                全选
              </label>
            </div>
            <div class="image-list">
              <div 
                v-for="(image, index) in scriptImages" 
                :key="image.id"
                class="image-item"
              >
                <label class="image-checkbox">
                  <input 
                    type="checkbox" 
                    v-model="selectedImages"
                    :value="image.id"
                  />
                  <span class="image-name">{{ image.title || `图片 ${index + 1}` }}</span>
                </label>
              </div>
            </div>
          </div>
          <div class="modal-actions">
            <button @click="closeDownloadModal" class="cancel-btn">取消</button>
            <button @click="confirmDownload" class="confirm-btn" :disabled="isDownloading">
              {{ isDownloading ? '下载中...' : '下载选中图片' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 下载进度模态框 -->
      <div v-if="showProgressModal" class="progress-modal-backdrop">
        <div class="progress-modal" @click.stop>
          <div class="modal-header">
            <h3>下载进度</h3>
          </div>
          <div class="modal-content">
            <div class="progress-info">
              <p>正在下载 {{ downloadedCount }}/{{ totalCount }} 张图片</p>
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: progressPercent + '%' }"></div>
              </div>
              <p class="current-file">{{ currentFileName }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ImageCarousel from './ImageCarousel.vue'
import scriptAPI from '@/utils/scriptAPI'

export default {
  name: 'ScriptDetailModal',
  components: {
    ImageCarousel
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    scriptId: {
      type: String,
      default: ''
    },
    scriptType: {
      type: String,
      default: 'custom'
    }
  },
  data() {
    return {
      currentTab: 'basic',
      scriptData: {},
      scriptImages: [],
      seriesVersions: [],
      isLoading: false,
      
      // 角色类型映射
      roleTeamMap: {
        'townsfolk': '镇民',
        'outsider': '外来者',
        'minion': '爪牙',
        'demon': '恶魔',
        'fabled': '传奇角色',
        'traveler': '旅行者',
        'unknown': '其他'
      },
      
      tabs: [
        { key: 'basic', name: '基本信息' },
        { key: 'roles', name: '角色数据' },
        { key: 'rules', name: '游戏规则' },
        { key: 'series', name: '系列版本' }
      ],

      // 图片下载相关
      showDownloadModal: false,
      selectedImages: [],
      isDownloading: false,
      downloadedCount: 0,
      totalCount: 0,
      progressPercent: 0,
      currentFileName: '',
      showProgressModal: false,
      
      // 角色展开状态
      expandedTeams: new Set(['default']), // 默认展开default团队
      expandedTeamsArray: ['default'], // 用于Vue响应式的数组版本
    }
  },
  computed: {
    roleTeams() {
      console.log('roleTeams计算属性被调用')
      console.log('当前scriptData:', this.scriptData)
      console.log('scriptData字段:', Object.keys(this.scriptData))
      console.log('content字段:', this.scriptData.content)
      console.log('content字段类型:', typeof this.scriptData.content)
      
      // 从服务器获取的数据解析角色数据
      if (this.scriptData.content && Array.isArray(this.scriptData.content)) {
        console.log('从服务器content字段解析角色数据')
        const parsedTeams = this.parseRolesFromContent()
        console.log('解析后的角色团队:', parsedTeams)
        return parsedTeams
      } else if (this.scriptData.originalJSON) {
        console.log('从服务器originalJSON字段解析角色数据')
        // 解析原始JSON字符串
        try {
          const originalData = JSON.parse(this.scriptData.originalJSON)
          if (Array.isArray(originalData)) {
            // 创建临时内容用于解析，不修改原始数据
            const tempContent = originalData
            const parsedTeams = this.parseRolesFromContentWithData(tempContent)
            console.log('解析后的角色团队:', parsedTeams)
            return parsedTeams
          }
        } catch (error) {
          console.log('解析originalJSON失败:', error)
        }
      }
      
      // 尝试从其他字段获取角色数据
      const roleData = this.scriptData.roleDetails || this.scriptData.roles || this.scriptData.roleList || []
      console.log('角色数据字段:', {
        roleDetails: this.scriptData.roleDetails,
        roles: this.scriptData.roles,
        roleList: this.scriptData.roleList
      })
      
      if (!roleData || roleData.length === 0) {
        console.log('未找到角色数据，返回默认团队')
        // 返回一个默认的团队，让用户可以展开
        return [{
          key: 'default',
          name: '角色信息',
          roles: [{
            id: 'no-data',
            name: '暂无角色数据',
            ability: '此剧本可能没有包含角色信息，或者角色数据格式不支持',
            team: 'default',
            image: null
          }]
        }]
      }
      
      console.log('找到角色数据，数量:', roleData.length)
      const teams = {}
      roleData.forEach(role => {
        const teamKey = role.team || role.teamType || 'unknown'
        if (!teams[teamKey]) {
          teams[teamKey] = {
            key: teamKey,
            name: this.roleTeamMap[teamKey] || '其他',
            roles: []
          }
        }
        teams[teamKey].roles.push({
          id: role.id || role.name,
          name: role.name,
          ability: role.ability || role.description || '暂无描述',
          team: teamKey,
          image: role.image || null
        })
      })
      
      const result = Object.values(teams)
      console.log('处理后的角色团队:', result)
      return result
    },
    
    firstNightRoles() {
      const roleData = this.scriptData.roleDetails || this.scriptData.roles || this.scriptData.roleList || []
      if (!roleData || roleData.length === 0) {
        // 尝试从内容中解析角色数据
        const content = this.scriptData.content || this.scriptData.script || this.scriptData.data || this.scriptData.roles || ''
        if (content) {
          try {
            const scriptObj = JSON.parse(content)
            if (Array.isArray(scriptObj)) {
              return scriptObj
                .filter(role => role.id !== '_meta' && role.name && role.firstNight > 0)
                .sort((a, b) => a.firstNight - b.firstNight)
            }
          } catch (e) {
            console.log('解析firstNightRoles失败:', e)
          }
        }
        return []
      }
      return roleData
        .filter(role => role.firstNight > 0)
        .sort((a, b) => a.firstNight - b.firstNight)
    },
    
    otherNightRoles() {
      const roleData = this.scriptData.roleDetails || this.scriptData.roles || this.scriptData.roleList || []
      if (!roleData || roleData.length === 0) {
        // 尝试从内容中解析角色数据
        const content = this.scriptData.content || this.scriptData.script || this.scriptData.data || this.scriptData.roles || ''
        if (content) {
          try {
            const scriptObj = JSON.parse(content)
            if (Array.isArray(scriptObj)) {
              return scriptObj
                .filter(role => role.id !== '_meta' && role.name && role.otherNight > 0)
                .sort((a, b) => a.otherNight - b.otherNight)
            }
          } catch (e) {
            console.log('解析otherNightRoles失败:', e)
          }
        }
        return []
      }
      return roleData
        .filter(role => role.otherNight > 0)
        .sort((a, b) => a.otherNight - b.otherNight)
    },
    
    // 监听selectedImages变化，自动更新selectAllImages状态
    selectAllImages: {
      get() {
        return this.scriptImages.length > 0 && this.selectedImages.length === this.scriptImages.length
      },
      set(value) {
        if (value) {
          this.selectedImages = this.scriptImages.map(img => img.id)
        } else {
          this.selectedImages = []
        }
      }
    }
  },
  mounted() {
    console.log('ScriptDetailModal mounted')
    console.log('mounted时的show:', this.show)
    console.log('mounted时的scriptId:', this.scriptId)
    if (this.show && this.scriptId) {
      console.log('mounted时触发loadScriptData')
      this.loadScriptData()
    } else {
      console.log('mounted时未触发loadScriptData，条件不满足')
    }
  },
  watch: {
    show(newVal) {
      console.log('show属性变化:', newVal)
      if (newVal && this.scriptId) {
        console.log('触发loadScriptData，因为show为true且scriptId存在')
        this.loadScriptData()
      } else {
        console.log('show变化但未触发loadScriptData，条件不满足')
      }
    },
    scriptId(newVal) {
      console.log('scriptId属性变化:', newVal)
      if (newVal && this.show) {
        console.log('触发loadScriptData，因为scriptId变化且show为true')
        this.loadScriptData()
      } else {
        console.log('scriptId变化但未触发loadScriptData，条件不满足')
      }
    },
    currentTab(newVal) {
      console.log('标签页切换到:', newVal)
      if (newVal === 'roles') {
        console.log('切换到角色数据标签页')
        console.log('当前角色团队:', this.roleTeams)
        console.log('当前scriptData:', this.scriptData)
        console.log('scriptData字段:', Object.keys(this.scriptData))
        console.log('content字段:', this.scriptData.content)
        console.log('script字段:', this.scriptData.script)
        console.log('roles字段:', this.scriptData.roles)
        
        // 如果scriptData为空，尝试重新加载数据
        if (!this.scriptData.content && !this.scriptData.script && !this.scriptData.roles) {
          console.log('scriptData中没有角色数据，尝试重新加载')
          this.loadScriptData()
        }
      } else if (newVal === 'series') {
        console.log('切换到系列版本标签页')
        console.log('当前seriesVersions:', this.seriesVersions)
        console.log('当前scriptId:', this.scriptId)
        
        // 如果系列数据为空，尝试重新加载基本信息
        if (!this.seriesVersions || this.seriesVersions.length === 0) {
          console.log('seriesVersions为空，尝试重新加载基本信息')
          this.loadBasicScriptData()
        }
      }
    },
    roleTeams: {
      handler(newTeams) {
        console.log('roleTeams变化，确保默认展开')
        console.log('新的团队数据:', newTeams)
        this.$nextTick(() => {
          if (newTeams.length > 0 && this.expandedTeamsArray.length === 0) {
            // 如果没有展开的团队，默认展开第一个
            this.expandedTeams.add(newTeams[0].key)
            this.expandedTeamsArray.push(newTeams[0].key)
            console.log('默认展开第一个团队:', newTeams[0].key)
          }
        })
      },
      immediate: false
    }
  },
  methods: {
    async loadScriptData() {
      if (!this.scriptId) {
        return
      }
      console.log('开始加载剧本数据，scriptId:', this.scriptId, 'scriptType:', this.scriptType)
      try {
        this.isLoading = true
        
        // 优先从服务器获取数据
        console.log('从服务器请求完整JSON数据')
        const fullScriptResult = await this.fetchFullScriptFromServer()
        
        if (fullScriptResult) {
          console.log('服务器返回完整数据，解析并显示')
          console.log('设置前的scriptData:', this.scriptData)
          this.scriptData = fullScriptResult
          console.log('设置后的scriptData:', this.scriptData)
          console.log('scriptData字段:', Object.keys(this.scriptData))
          console.log('content字段:', this.scriptData.content)
          this.parseAndDisplayRoleData()
          
          // 加载系列信息
          await this.loadBasicScriptData()
          
          // 存储到本地供下次使用
          this.saveFullScriptDataToLocal(fullScriptResult)
        } else {
          console.log('服务器没有返回完整数据，尝试从本地缓存获取')
          // 如果服务器没有数据，尝试从本地缓存获取
          const cachedFullData = this.getCachedFullScriptData()
          if (cachedFullData) {
            console.log('从本地缓存获取到完整数据')
            this.scriptData = cachedFullData
            this.parseAndDisplayRoleData()
          } else {
            console.log('本地缓存也没有数据，使用基本信息')
            await this.loadBasicScriptData()
          }
        }
        
      } catch (error) {
        console.error('加载剧本数据失败:', error)
        // 如果出错，尝试加载基本信息
        await this.loadBasicScriptData()
      } finally {
        this.isLoading = false
      }
    },
    
    // 缓存相关方法
    getCachedData() {
      try {
        const cacheKey = `script_detail_${this.scriptId}`
        const cached = localStorage.getItem(cacheKey)
        if (cached) {
          const data = JSON.parse(cached)
          // 检查缓存是否过期（24小时）
          if (Date.now() - data.timestamp < 24 * 60 * 60 * 1000) {
            return data
          }
        }
      } catch (error) {
        console.error('读取缓存失败:', error)
      }
      return null
    },
    
    cacheData() {
      try {
        const cacheKey = `script_detail_${this.scriptId}`
        const cacheData = {
          scriptData: this.scriptData,
          scriptImages: this.scriptImages,
          seriesVersions: this.seriesVersions,
          timestamp: Date.now()
        }
        localStorage.setItem(cacheKey, JSON.stringify(cacheData))
      } catch (error) {
        console.error('缓存数据失败:', error)
      }
    },
    
    clearCache() {
      try {
        // 清除所有剧本详情缓存
        const keys = Object.keys(localStorage)
        keys.forEach(key => {
          if (key.startsWith('script_detail_')) {
            localStorage.removeItem(key)
          }
        })
        console.log('已清除剧本详情缓存')
      } catch (error) {
        console.error('清除缓存失败:', error)
      }
    },
    
    // 从剧本内容中解析角色信息
    parseRolesFromContent() {
      return this.parseRolesFromContentWithData(this.scriptData.content)
    },
    
    // 使用指定数据解析角色信息（避免在computed中修改数据）
    parseRolesFromContentWithData(content) {
      const teams = {}
      
      console.log('parseRolesFromContentWithData被调用')
      console.log('传入的content:', content)
      console.log('内容类型:', typeof content)
      
      // 处理字符串类型的content
      if (typeof content === 'string') {
        console.log('content是字符串，尝试解析为JSON')
        try {
          content = JSON.parse(content)
          console.log('解析后的content:', content)
        } catch (e) {
          console.error('解析字符串content失败:', e)
          // 返回默认团队
          return [{
            key: 'default',
            name: '角色信息',
            roles: [{
              id: 'no-data',
              name: '暂无角色数据',
              ability: '此剧本可能没有包含角色信息，或者角色数据格式不支持',
              team: 'default',
              image: null
            }]
          }]
        }
      }
      
      if (!content || !Array.isArray(content)) {
        console.log('剧本内容为空或不是数组，无法解析角色信息，返回默认团队')
        // 返回一个默认的团队，让用户可以展开
        return [{
          key: 'default',
          name: '角色信息',
          roles: [{
            id: 'no-data',
            name: '暂无角色数据',
            ability: '此剧本可能没有包含角色信息，或者角色数据格式不支持',
            team: 'default',
            image: null
          }]
        }]
      }
      
      // 尝试解析JSON格式的角色数据
      try {
        console.log('开始解析JSON内容')
        // content已经是数组格式，直接使用
        const scriptObj = content
        console.log('解析后的对象:', scriptObj)
        console.log('对象类型:', typeof scriptObj)
        console.log('是否为数组:', Array.isArray(scriptObj))
        
        // 检查是否是数组格式（如你提供的JSON文件）
        if (Array.isArray(scriptObj)) {
          console.log('检测到数组格式的剧本数据，角色数量:', scriptObj.length)
          scriptObj.forEach((role, index) => {
            console.log(`处理角色 ${index}:`, role)
            
            // 跳过元数据对象（id为_meta的对象）
            if (role.id === '_meta') {
              console.log('跳过元数据对象')
              return
            }
            
            // 检查是否是角色对象（有name和ability字段）
            if (role.name && role.ability) {
              console.log('找到有效角色:', role.name)
              const teamKey = role.team || 'unknown'
              if (!teams[teamKey]) {
                teams[teamKey] = {
                  key: teamKey,
                  name: this.roleTeamMap[teamKey] || '其他',
                  roles: []
                }
                console.log('创建新团队:', teamKey)
              }
              teams[teamKey].roles.push({
                id: role.id || role.name,
                name: role.name,
                ability: role.ability,
                team: teamKey,
                image: role.image || null
              })
              console.log('角色已添加到团队:', teamKey)
            } else {
              console.log('跳过无效角色:', role)
            }
          })
          
          const result = Object.values(teams)
          console.log('最终解析结果:', result)
          return result
        }
        
        // 检查是否有roles字段
        if (scriptObj.roles && Array.isArray(scriptObj.roles)) {
          scriptObj.roles.forEach(role => {
            const teamKey = role.team || role.teamType || 'unknown'
            if (!teams[teamKey]) {
              teams[teamKey] = {
                key: teamKey,
                name: this.roleTeamMap[teamKey] || '其他',
                roles: []
              }
            }
            teams[teamKey].roles.push({
              id: role.id || role.name,
              name: role.name,
              ability: role.ability || role.description || '暂无描述',
              team: teamKey,
              image: role.image || null
            })
          })
          return Object.values(teams)
        }
      } catch (e) {
        console.log('剧本内容不是JSON格式，尝试其他解析方式:', e)
        
        // 如果JSON解析失败，尝试从文本中提取角色信息
        const roles = []
        
        // 简单的角色名称提取（这里可以根据实际数据格式调整）
        const nameMatches = content.match(/"name":\s*"([^"]+)"/g)
        if (nameMatches) {
          nameMatches.forEach(match => {
            const name = match.match(/"name":\s*"([^"]+)"/)[1]
            roles.push({
              id: name,
              name: name,
              ability: '角色能力描述',
              team: 'unknown'
            })
          })
        }
        
        if (roles.length > 0) {
          teams.unknown = {
            key: 'unknown',
            name: '其他',
            roles: roles
          }
          return Object.values(teams)
        }
      }
      
      console.log('无法从剧本内容中解析角色信息，返回默认团队')
      // 返回一个默认的团队，让用户可以展开
      return [{
        key: 'default',
        name: '角色信息',
        roles: [{
          id: 'no-data',
          name: '暂无角色数据',
          ability: '此剧本可能没有包含角色信息，或者角色数据格式不支持',
          team: 'default',
          image: null
        }]
      }]
    },
    
    // 从本地缓存获取完整剧本数据
    getCachedFullScriptData() {
      try {
        const userId = this.getCurrentUserId()
        const storageKey = `full_script_${userId}_${this.scriptType}_${this.scriptId}`
        const cachedData = localStorage.getItem(storageKey)
        if (cachedData) {
          const data = JSON.parse(cachedData)
          // 检查缓存是否过期（24小时）
          if (Date.now() - data.timestamp < 24 * 60 * 60 * 1000) {
            return data.scriptData
          }
        }
      } catch (error) {
        console.error('读取缓存失败:', error)
      }
      return null
    },
    
    // 从服务器获取完整剧本数据
    async fetchFullScriptFromServer() {
      try {
        console.log('从服务器获取完整剧本数据')
        
        // 尝试不同的API方法获取完整数据
        const methods = [
          () => scriptAPI.getScript(this.scriptId, this.scriptType),
          () => scriptAPI.getScriptById(this.scriptId, this.scriptType),
          () => scriptAPI.getAllScripts({ scriptId: this.scriptId, type: this.scriptType })
        ]
        
        for (const method of methods) {
          try {
            const result = await method()
            console.log('API调用结果:', result)
            
            if (result.success && result.data) {
              console.log('API返回的数据字段:', Object.keys(result.data))
              console.log('content字段:', result.data.content)
              // 检查是否有角色数据
              if (result.data.content && Array.isArray(result.data.content)) {
                console.log('找到包含角色数据的完整数据，content长度:', result.data.content.length)
                return result.data
              } else {
                console.log('数据中没有有效的content字段')
              }
            }
          } catch (error) {
            console.log('API调用失败:', error)
          }
        }
        
        console.log('所有API方法都没有返回完整数据')
        return null
      } catch (error) {
        console.error('从服务器获取完整数据失败:', error)
        return null
      }
    },
    
    // 解析并显示角色数据
    parseAndDisplayRoleData() {
      console.log('解析并显示角色数据')
      console.log('当前scriptData:', this.scriptData)
      
      // 触发roleTeams计算属性重新计算
      this.$forceUpdate()
    },
    
    // 保存完整剧本数据到本地
    saveFullScriptDataToLocal(scriptData) {
      try {
        const userId = this.getCurrentUserId()
        const storageKey = `full_script_${userId}_${this.scriptType}_${this.scriptId}`
        const cacheData = {
          scriptData: scriptData,
          timestamp: Date.now()
        }
        localStorage.setItem(storageKey, JSON.stringify(cacheData))
        console.log('完整剧本数据已保存到本地:', storageKey)
      } catch (error) {
        console.error('保存完整剧本数据失败:', error)
      }
    },
    
    // 加载基本信息（图片、系列等）
    async loadBasicScriptData() {
      console.log('loadBasicScriptData开始，当前scriptId:', this.scriptId)
      try {
        const [imagesResult, allSeriesResult] = await Promise.all([
          scriptAPI.getScriptImages(this.scriptId),
          scriptAPI.getScriptSeries()
        ])
        
        if (imagesResult.success) {
          this.scriptImages = imagesResult.data?.images || []
        } else {
          this.scriptImages = []
        }
        
        // 查找当前剧本所属系列及所有版本
        console.log('开始查找系列信息，当前scriptId:', this.scriptId)
        console.log('所有系列数据:', allSeriesResult.data)
        
        if (allSeriesResult.success) {
          let found = false
          for (const series of allSeriesResult.data) {
            console.log('检查系列:', series.name, '版本数量:', series.versions ? series.versions.length : 0)
            if (series.versions && series.versions.length > 0) {
              console.log('系列版本列表:', series.versions.map(v => ({ id: v.id, name: v.name, version: v.version })))
            }
            const version = (series.versions || []).find(v => v.id === this.scriptId)
            if (version) {
              console.log('找到当前剧本所属系列:', series.name)
              console.log('匹配的版本:', version)
              this.seriesVersions = series.versions || []
              console.log('设置系列版本:', this.seriesVersions)
              found = true
              break
            } else {
              console.log('在系列', series.name, '中未找到ID为', this.scriptId, '的版本')
            }
          }
          if (!found) {
            console.log('未找到当前剧本所属的系列')
            console.log('尝试查找所有系列中的所有版本ID:')
            allSeriesResult.data.forEach(series => {
              if (series.versions) {
                series.versions.forEach(v => {
                  console.log('系列', series.name, '中的版本ID:', v.id, '名称:', v.name)
                })
              }
            })
            this.seriesVersions = []
          }
        } else {
          console.log('获取系列数据失败:', allSeriesResult.error)
          this.seriesVersions = []
        }
      } catch (error) {
        console.error('加载基本信息失败:', error)
      }
    },
    
    // 获取当前用户ID
    getCurrentUserId() {
      try {
        if (typeof window !== 'undefined' && window.authAPI) {
          const currentUser = window.authAPI.getCurrentUser()
          if (currentUser && currentUser.id) {
            return currentUser.id
          }
        }
      } catch (error) {
        console.log('无法获取用户ID:', error)
      }
      return 'anonymous'
    },
    
    // 切换团队展开状态
    toggleTeamExpansion(teamKey) {
      console.log('切换团队展开状态:', teamKey)
      console.log('当前展开的团队:', Array.from(this.expandedTeams))
      
      if (this.expandedTeams.has(teamKey)) {
        this.expandedTeams.delete(teamKey)
        // 从数组中移除
        const index = this.expandedTeamsArray.indexOf(teamKey)
        if (index > -1) {
          this.expandedTeamsArray.splice(index, 1)
        }
        console.log('收起团队:', teamKey)
      } else {
        this.expandedTeams.add(teamKey)
        // 添加到数组
        this.expandedTeamsArray.push(teamKey)
        console.log('展开团队:', teamKey)
      }
      
      // 强制触发响应式更新
      this.expandedTeamsArray = [...this.expandedTeamsArray]
      
      console.log('切换后的展开团队:', Array.from(this.expandedTeams))
      console.log('切换后的展开团队数组:', this.expandedTeamsArray)
      
      // 强制更新视图
      this.$forceUpdate()
    },
    
    // 检查团队是否展开
    isTeamExpanded(teamKey) {
      // 确保至少有一个团队展开
      if (this.expandedTeamsArray.length === 0 && this.roleTeams.length > 0) {
        console.log('没有展开的团队，自动展开第一个')
        const firstTeamKey = this.roleTeams[0].key
        this.expandedTeams.add(firstTeamKey)
        this.expandedTeamsArray = [firstTeamKey]
        return teamKey === firstTeamKey
      }
      
      const isExpanded = this.expandedTeamsArray.includes(teamKey)
      console.log(`检查团队 ${teamKey} 是否展开:`, isExpanded, '当前展开数组:', this.expandedTeamsArray)
      return isExpanded
    },
    

    

    
    // 重新加载剧本数据
    async reloadScriptData() {
      console.log('手动重新加载剧本数据')
      console.log('当前scriptId:', this.scriptId)
      console.log('当前scriptType:', this.scriptType)
      
      // 检查localStorage中的所有键
      const allKeys = Object.keys(localStorage)
      console.log('所有localStorage键:', allKeys)
      
      // 查找包含当前scriptId的键
      const relevantKeys = allKeys.filter(key => key.includes(this.scriptId))
      console.log('包含当前scriptId的键:', relevantKeys)
      
      // 查找包含剧本名称的键
      if (this.scriptData.name) {
        const nameKeys = allKeys.filter(key => key.includes(this.scriptData.name))
        console.log('包含剧本名称的键:', nameKeys)
        relevantKeys.push(...nameKeys)
      }
      
      // 查找包含script的键
      const scriptKeys = allKeys.filter(key => key.includes('script'))
      console.log('包含script的键:', scriptKeys)
      relevantKeys.push(...scriptKeys)
      
      // 尝试从每个相关键获取数据
      for (const key of relevantKeys) {
        try {
          const data = localStorage.getItem(key)
          if (data) {
            const parsedData = JSON.parse(data)
            console.log(`键 ${key} 的数据:`, parsedData)
            
            // 检查是否是数组格式的剧本数据
            if (Array.isArray(parsedData)) {
              console.log('找到数组格式的剧本数据')
              this.scriptData.content = JSON.stringify(parsedData)
              console.log('已设置scriptData.content')
              return
            }
            
            // 检查是否有content字段
            if (parsedData.content) {
              console.log('找到content字段')
              this.scriptData.content = parsedData.content
              return
            }
          }
        } catch (e) {
          console.log(`解析键 ${key} 失败:`, e)
        }
      }
      
      console.log('未找到相关的剧本数据')
      
      // 如果本地没有找到数据，尝试从服务器获取
      console.log('尝试从服务器获取完整数据')
      await this.fetchFullScriptDataFromServer()
    },
    
    // 从服务器获取完整的剧本数据
    async fetchFullScriptDataFromServer() {
      try {
        console.log('从服务器获取完整剧本数据')
        
        // 尝试获取剧本的完整内容
        const fullScriptResult = await scriptAPI.getScript(this.scriptId, this.scriptType)
        if (fullScriptResult.success) {
          console.log('从服务器获取的完整剧本数据:', fullScriptResult.data)
          
          // 合并服务器数据
          this.scriptData = {
            ...this.scriptData,
            ...fullScriptResult.data
          }
          
          // 如果服务器数据中有角色信息，保存到本地
          if (fullScriptResult.data.content || fullScriptResult.data.script || fullScriptResult.data.roles) {
            this.saveScriptDataToLocal(fullScriptResult.data)
          }
        } else {
          console.log('服务器没有返回完整数据')
        }
      } catch (error) {
        console.error('从服务器获取完整数据失败:', error)
      }
    },
    
    // 保存剧本数据到本地
    saveScriptDataToLocal(scriptData) {
      try {
        const userId = this.getCurrentUserId()
        const storageKey = `script_file_${userId}_${this.scriptType}_${this.scriptId}`
        localStorage.setItem(storageKey, JSON.stringify(scriptData))
        console.log('剧本数据已保存到本地:', storageKey)
      } catch (error) {
        console.error('保存剧本数据到本地失败:', error)
      }
    },
    
    // 强制加载完整数据
    async forceLoadFullData() {
      console.log('强制加载完整数据')
      console.log('当前scriptId:', this.scriptId)
      console.log('当前scriptType:', this.scriptType)
      
      try {
        // 1. 尝试从服务器获取完整数据
        console.log('1. 从服务器获取完整数据')
        const fullScriptResult = await scriptAPI.getScript(this.scriptId, this.scriptType)
        console.log('getScript返回的完整数据:', fullScriptResult)
        
        // 如果getScript没有返回完整数据，尝试getScriptById
        if (!fullScriptResult.success || !fullScriptResult.data) {
          console.log('getScript失败，尝试getScriptById')
          const scriptByIdResult = await scriptAPI.getScriptById(this.scriptId, this.scriptType)
          console.log('getScriptById返回的数据:', scriptByIdResult)
          
          if (scriptByIdResult.success && scriptByIdResult.data) {
            fullScriptResult.data = scriptByIdResult.data
          }
        }
        
        if (fullScriptResult.success && fullScriptResult.data) {
          console.log('服务器数据成功，合并到scriptData')
          this.scriptData = {
            ...this.scriptData,
            ...fullScriptResult.data
          }
          console.log('合并后的scriptData:', this.scriptData)
          
          // 保存到本地
          this.saveScriptDataToLocal(this.scriptData)
        } else {
          console.log('服务器没有返回完整数据，尝试其他方法')
        }
        
        // 2. 如果服务器数据不完整，尝试从本地存储查找
        if (!this.scriptData.content && !this.scriptData.script && !this.scriptData.roles) {
          console.log('2. 从本地存储查找完整数据')
          await this.reloadScriptData()
        }
        
        // 3. 如果还是没有数据，尝试模拟数据
        if (!this.scriptData.content && !this.scriptData.script && !this.scriptData.roles) {
          console.log('3. 尝试模拟角色数据')
          this.simulateRoleData()
        }
        
      } catch (error) {
        console.error('强制加载完整数据失败:', error)
      }
    },
    
    // 模拟角色数据（用于测试）
    simulateRoleData() {
      console.log('模拟角色数据')
      const mockContent = JSON.stringify([
        {
          "id": "_meta",
          "name": "暗流涌动",
          "description": "乌云在鸦木布拉夫的天空中翻滚着..."
        },
        {
          "id": "1_82",
          "name": "乞丐",
          "ability": "你只能使用投票标记投票。死亡的玩家可以将他的投票标记给你，如果他这么做，你会得知他的阵营。你不会中毒和醉酒。",
          "team": "traveler",
          "firstNight": 0,
          "otherNight": 0
        },
        {
          "id": "1_93", 
          "name": "替罪羊",
          "ability": "如果你的阵营的一名玩家被处决，你可能会代替他被处决。",
          "team": "traveler",
          "firstNight": 0,
          "otherNight": 0
        }
      ])
      
      this.scriptData.content = mockContent
      console.log('已设置模拟数据到scriptData.content')
    },
    
    // 尝试从本地存储获取角色数据
    tryLoadRoleDataFromStorage() {
      try {
        // 尝试从不同的本地存储键获取角色数据
        const userId = this.getCurrentUserId()
        const storageKeys = [
          // 优先检查用户特定的存储键
          `script_file_${userId}_${this.scriptType}_${this.scriptId}`,
          `script_file_${this.scriptId}`,
          `script_file_custom_${this.scriptId}`,
          `script_file_${this.scriptType}_${this.scriptId}`,
          `townsquare_scripts_cache`,
          `townsquare_scripts_cache_${this.scriptId}`
        ]
        
        // 尝试获取当前用户ID
        const currentUserId = this.getCurrentUserId()
        
        // 添加用户特定的键
        storageKeys.push(
          `script_file_${currentUserId}_${this.scriptType}_${this.scriptId}`,
          `townsquare_scripts_cache_${currentUserId}`
        )
        
        // 添加可能的剧本名称键
        if (this.scriptData.name) {
          storageKeys.push(
            `script_file_${this.scriptData.name}`,
            `script_file_${currentUserId}_${this.scriptData.name}`,
            `暗流涌动`,
            `暗流涌动.json`
          )
        }
        
        console.log('尝试从本地存储获取角色数据，键:', storageKeys)
        console.log('当前scriptId:', this.scriptId)
        console.log('当前scriptType:', this.scriptType)
        
        // 先列出所有localStorage键
        const allKeys = Object.keys(localStorage)
        console.log('所有localStorage键:', allKeys)
        
        for (const key of storageKeys) {
          const cachedData = localStorage.getItem(key)
          if (cachedData) {
            try {
              const data = JSON.parse(cachedData)
              console.log(`从键 ${key} 获取到数据:`, data)
              
              // 检查是否是数组格式的剧本数据
              if (Array.isArray(data)) {
                console.log('检测到数组格式的剧本数据')
                this.scriptData.content = JSON.stringify(data)
                return
              }
              
              // 检查是否有content字段
              if (data.content) {
                console.log('检测到content字段')
                this.scriptData.content = data.content
                return
              }
              
              // 检查是否有script字段
              if (data.script) {
                console.log('检测到script字段')
                this.scriptData.script = data.script
                return
              }
              
              // 检查是否有data字段
              if (data.data) {
                console.log('检测到data字段')
                this.scriptData.data = data.data
                return
              }
              
              // 检查是否有roles字段
              if (data.roles) {
                console.log('检测到roles字段')
                this.scriptData.roles = data.roles
                return
              }
              
            } catch (e) {
              console.log(`解析键 ${key} 的数据失败:`, e)
            }
          } else {
            console.log(`键 ${key} 不存在`)
          }
        }
        
        console.log('未在本地存储中找到角色数据')
      } catch (error) {
        console.error('从本地存储获取角色数据失败:', error)
      }
    },
    
    switchToVersion(version) {
      if (version.id === this.scriptId) return
      this.$emit('switch-version', version.id)
    },
    
    downloadImages() {
      if (this.scriptImages.length === 0) {
        alert('此剧本没有图片可下载')
        return
      }
      
      // 默认全选所有图片
      this.selectedImages = this.scriptImages.map(img => img.id)
      this.selectAllImages = true
      this.showDownloadModal = true
    },
    
    async useScript() {
      try {
        // 检查是否有有效的剧本数据
        if (!this.scriptData || !this.scriptId) {
          console.error("❌ 无效的剧本数据");
          return;
        }

        // 记录使用次数
        await scriptAPI.useScript(this.scriptId);

        // 如果剧本包含角色数据，设置自定义角色
        if (this.scriptData.content && Array.isArray(this.scriptData.content)) {
          // 过滤掉_meta数据，只保留角色
          const roles = this.scriptData.content.filter(item => item.id !== '_meta');
          this.$store.commit("setCustomRoles", roles);
        }
        
        // 设置剧本版本信息
        this.$store.commit("setEdition", {
          id: this.scriptId,
          name: this.scriptData.name,
          author: this.scriptData.author || "未知作者",
          description: this.scriptData.description || "",
          isOfficial: this.scriptType === 'official'
        });
        
        // 关闭剧本详情模态框并通知父组件关闭所有界面
        this.$emit('close');
        this.$emit('use-script-complete'); // 新增事件通知父组件剧本使用完成
        
        // 使用控制台日志替代alert弹框
        console.log(`✅ 剧本"${this.scriptData.name}"已加载成功！`);
      } catch (error) {
        console.error("❌ 使用剧本失败:", error.message);
      }
    },
    
    closeModal() {
      this.$emit('close')
    },

    // 图片下载模态框相关方法

    async confirmDownload() {
      if (this.selectedImages.length === 0) {
        alert('请至少选择一张图片进行下载')
        return
      }

      this.isDownloading = true
      this.downloadedCount = 0
      this.totalCount = this.selectedImages.length
      this.progressPercent = 0
      this.showProgressModal = true

      for (const imageId of this.selectedImages) {
        try {
          const image = this.scriptImages.find(img => img.id === imageId)
          if (!image) continue

          this.currentFileName = image.title || `图片 ${this.downloadedCount + 1}`
          
          // 构建图片URL
          const imageUrl = `${this.$config.API_BASE_URL}/images/${this.scriptId}/${image.filename}`
          
          const result = await scriptAPI.downloadImage(imageUrl)
          if (result.success) {
            this.downloadedCount++
            this.progressPercent = (this.downloadedCount / this.totalCount) * 100
          } else {
            console.error('下载图片失败:', result.error)
            alert(`下载图片失败: ${result.error}`)
            this.downloadedCount++ // 继续尝试下载其他图片
            this.progressPercent = (this.downloadedCount / this.totalCount) * 100
          }
        } catch (error) {
          console.error('下载图片失败:', error)
          alert('下载图片失败，请检查网络或图片链接')
          this.downloadedCount++ // 继续尝试下载其他图片
          this.progressPercent = (this.downloadedCount / this.totalCount) * 100
        }
      }

      this.isDownloading = false
      this.showProgressModal = false
      alert('所有选中图片下载完成！')
    },

    closeDownloadModal() {
      this.showDownloadModal = false
    },

    closeProgressModal() {
      this.showProgressModal = false
    }
  }
}
</script>

<style scoped>
.script-detail-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.script-detail-modal {
  background: #1a1a1a;
  border-radius: 12px;
  width: 90%;
  max-width: 1200px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  position: relative;
  border: 1px solid rgba(255, 215, 0, 0.2);
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background: none;
  border: none;
  color: #fff;
  font-size: 24px;
  cursor: pointer;
  z-index: 10;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.images-section {
  width: 100%;
  height: 300px;
  overflow: hidden;
  border-radius: 12px 12px 0 0;
}

.no-images-placeholder {
  width: 100%;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.02);
  border-radius: 12px 12px 0 0;
  border-bottom: 1px solid rgba(255, 215, 0, 0.1);
}

.placeholder-content {
  text-align: center;
  color: #666;
}

.placeholder-icon {
  font-size: 48px;
  margin-bottom: 10px;
  opacity: 0.5;
}

.placeholder-content p {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #999;
}

.placeholder-content small {
  font-size: 12px;
  color: #666;
}

.tabs-nav {
  display: flex;
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 215, 0, 0.2);
  padding: 0 20px;
}

.tab-btn {
  background: none;
  border: none;
  color: #ccc;
  padding: 15px 20px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
  font-size: 14px;
}

.tab-btn:hover {
  color: #fff;
  background: rgba(255, 255, 255, 0.05);
}

.tab-btn.active {
  color: #ffd700;
  border-bottom-color: #ffd700;
}

.tab-content {
  padding: 20px;
  height: 100%;
}

.tab-panel {
  min-height: 400px;
  overflow-y: auto;
  max-height: calc(90vh - 200px);
}

/* 基本信息样式 */
.basic-info {
  color: #fff;
}

.script-header {
  margin-bottom: 20px;
}

.script-name {
  font-size: 24px;
  margin: 0 0 10px 0;
  color: #ffd700;
}

.script-meta {
  display: flex;
  gap: 20px;
  color: #ccc;
  font-size: 14px;
}

.script-description {
  margin-top: 20px;
}

.script-description h3 {
  color: #ffd700;
  margin-bottom: 10px;
}

.script-description p {
  line-height: 1.6;
  color: #ccc;
}

/* 角色数据样式 */
.roles-section {
  color: #fff;
}

.role-team {
  margin-bottom: 30px;
  border: 1px solid rgba(255, 215, 0, 0.2);
  border-radius: 8px;
  overflow: hidden;
}

.team-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  background: rgba(255, 215, 0, 0.1);
  cursor: pointer;
  transition: background 0.3s;
}

.team-header:hover {
  background: rgba(255, 215, 0, 0.2);
}

.team-title {
  color: #ffd700;
  margin: 0;
  font-size: 18px;
  flex: 1;
}

.team-count {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin-left: 10px;
}

.expand-icon {
  color: #ffd700;
  font-size: 16px;
  transition: transform 0.3s;
}

.expand-icon.expanded {
  transform: rotate(90deg);
}

.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  padding: 20px;
  transition: all 0.3s ease;
}

.role-card {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 215, 0, 0.2);
  border-radius: 8px;
  padding: 15px;
  transition: all 0.3s;
}

.role-card:hover {
  background: rgba(255, 255, 255, 0.08);
  border-color: rgba(255, 215, 0, 0.4);
}

.role-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.role-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.role-name {
  color: #ffd700;
  margin: 0;
  font-size: 16px;
}

.role-ability {
  margin-bottom: 10px;
}

.role-ability p {
  color: #ccc;
  line-height: 1.5;
  margin: 0;
}

/* 游戏规则样式 */
.rules-section {
  color: #fff;
}

.night-order {
  margin-bottom: 30px;
}

.night-order h3 {
  color: #ffd700;
  margin-bottom: 15px;
}

.order-lists {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.first-night, .other-nights {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 215, 0, 0.2);
  border-radius: 8px;
  padding: 15px;
}

.first-night h4, .other-nights h4 {
  color: #ffd700;
  margin-bottom: 10px;
}

.first-night ol, .other-nights ol {
  color: #ccc;
  line-height: 1.6;
  padding-left: 20px;
}

/* 系列版本样式 */
.series-section {
  color: #fff;
}

.series-section h3 {
  color: #ffd700;
  margin-bottom: 15px;
}

.series-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.version-item {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 215, 0, 0.2);
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.version-item:hover {
  background: rgba(255, 255, 255, 0.08);
  border-color: rgba(255, 215, 0, 0.4);
}

.version-item.current {
  border-color: #ffd700;
  background: rgba(255, 215, 0, 0.1);
}

.version-info h4 {
  color: #ffd700;
  margin: 0 0 5px 0;
}

.version-number {
  color: #ccc;
  font-size: 14px;
}

.version-status {
  display: flex;
  gap: 10px;
}

.current-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  background: rgba(255, 215, 0, 0.2);
  color: #ffd700;
}

.no-series {
  text-align: center;
  color: #999;
  padding: 40px 20px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  padding: 20px;
  border-top: 1px solid rgba(255, 215, 0, 0.2);
  background: rgba(255, 255, 255, 0.02);
  flex-shrink: 0;
}

.action-btn {
  background: rgba(255, 215, 0, 0.2);
  color: #ffd700;
  border: 1px solid rgba(255, 215, 0, 0.3);
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.action-btn:hover {
  background: rgba(255, 215, 0, 0.3);
  border-color: rgba(255, 215, 0, 0.5);
}

.download-btn {
  background: rgba(76, 175, 80, 0.2);
  color: #4caf50;
  border-color: rgba(76, 175, 80, 0.3);
}

.download-btn:hover {
  background: rgba(76, 175, 80, 0.3);
  border-color: rgba(76, 175, 80, 0.5);
}

/* 图片下载模态框样式 */
.download-modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1001;
}

.download-modal {
  background: #1a1a1a;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  position: relative;
  border: 1px solid rgba(255, 215, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid rgba(255, 215, 0, 0.2);
  background: rgba(255, 255, 255, 0.05);
}

.modal-header h3 {
  color: #ffd700;
  margin: 0;
}

.modal-content {
  padding: 20px;
}

.modal-content-area {
  flex: 1;
  overflow-y: auto;
}

.download-options {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 215, 0, 0.2);
}

.select-all {
  display: flex;
  align-items: center;
  color: #ccc;
  font-size: 14px;
  cursor: pointer;
}

.select-all input {
  margin-right: 8px;
  transform: scale(1.2);
}

.image-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.image-item {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 215, 0, 0.2);
  border-radius: 8px;
  padding: 10px 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.image-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
}

.image-checkbox input {
  transform: scale(1.2);
}

.image-name {
  color: #ccc;
  font-size: 14px;
}

.modal-actions {
  display: flex;
  justify-content: space-between;
  padding: 15px 20px;
  border-top: 1px solid rgba(255, 215, 0, 0.2);
  background: rgba(255, 255, 255, 0.02);
}

.cancel-btn, .confirm-btn {
  background: rgba(255, 215, 0, 0.2);
  color: #ffd700;
  border: 1px solid rgba(255, 215, 0, 0.3);
  padding: 8px 15px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.cancel-btn:hover {
  background: rgba(255, 215, 0, 0.3);
  border-color: rgba(255, 215, 0, 0.5);
}

.confirm-btn:hover {
  background: rgba(255, 215, 0, 0.3);
  border-color: rgba(255, 215, 0, 0.5);
}

.confirm-btn:disabled {
  background: rgba(255, 215, 0, 0.1);
  color: #ccc;
  border-color: rgba(255, 215, 0, 0.2);
  cursor: not-allowed;
}

/* 下载进度模态框样式 */
.progress-modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1002;
}

.progress-modal {
  background: #1a1a1a;
  border-radius: 12px;
  width: 90%;
  max-width: 400px;
  max-height: 300px;
  overflow-y: auto;
  position: relative;
  border: 1px solid rgba(255, 215, 0, 0.2);
}

.progress-info {
  padding: 20px;
  text-align: center;
  color: #fff;
}

.progress-info p {
  margin-bottom: 10px;
  font-size: 16px;
}

.progress-bar {
  height: 10px;
  background: #333;
  border-radius: 5px;
  margin-bottom: 10px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #ffd700;
  border-radius: 5px;
  transition: width 0.3s ease-in-out;
}

.current-file {
  font-size: 14px;
  color: #ccc;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .script-detail-modal {
    width: 95%;
    max-height: 95vh;
  }
  
  .tabs-nav {
    flex-wrap: wrap;
  }
  
  .tab-btn {
    padding: 10px 15px;
    font-size: 12px;
  }
  
  .roles-grid {
    grid-template-columns: 1fr;
  }
  
  .order-lists {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>